//
//  HRGoodsSearchViewController.m
//  haierapp
//
//  Created by zhang on 14-8-11.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HRGoodsSearchViewController.h"
#import "HRGoodsListViewController.h"

#import "HRProgressHUD.h"


#define SEARCH_VIEW_STATUS_HISTORY 1 //当前显示历史搜索记录
#define SEARCH_VIEW_STATUS_HOT  2   //当前显示搜索热词

#define KEYNAME_SEARCHHISTORY_USER_DEFAULTS @"searchHistory"

@interface HRGoodsSearchViewController ()
{
    NSArray *_historySearchArray;//搜索历史记录
    NSArray *_searchHotArray;//搜索热词
    
    int _curStatus;//搜索页面当前状态（热词、历史搜索记录）
    
    UITextField *_searchBox;
    UIButton *_clearHistoryButton;//清除历史记录按钮

}
@end

@implementation HRGoodsSearchViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    
    
    //导航栏加入搜索框
    NavigationViewController *navigationController=(NavigationViewController *)self.navigationController;
    _searchBox = [navigationController showGoodsSearch:self placeholder:@"请输入搜索词" withSearchAction:@selector(onSearchButtonActive:)];
    
    //搜索页面，当前显示状态
    if ([_searchText isEqualToString:@""] || _searchText==nil) {
        [self showSearchHistoryList];
        
    }else{
        [self showSearchHotList];
    }
    
    
    UIImage *grayImage=[[UIImage imageNamed:@"grey_border"]resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    
    _clearHistoryButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [_clearHistoryButton setTitle:@"清除搜索历史" forState:UIControlStateNormal];
    [_clearHistoryButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _clearHistoryButton.titleLabel.font=[UIFont fontWithName:FONT_NAME_DEFAULT size:12.0f];
    _clearHistoryButton.titleLabel.textColor=[UIColor blackColor];
    [_clearHistoryButton setBackgroundImage:grayImage forState:UIControlStateNormal];
    [_clearHistoryButton addTarget:self action:@selector(clearSearchHistory) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    //聚焦搜索框
    [_searchBox becomeFirstResponder];
}

-(void)viewWillDisappear:(BOOL)animated{
    
    //隐藏键盘
    [_searchBox resignFirstResponder];
    
    [super viewWillDisappear:animated];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Methods

//在导航条上显示搜索栏
-(void)showSearchBarInNavBar{
    _searchBox=[[UITextField alloc]initWithFrame:CGRectMake(0, 0, 320,29)];
    _searchBox.borderStyle=UITextBorderStyleNone;
    _searchBox.layer.cornerRadius=2.0f;
    
    _searchBox.clearButtonMode=UITextFieldViewModeWhileEditing;
    _searchBox.delegate=self;
    
    _searchBox.backgroundColor=[UIColor whiteColor];
    self.navigationItem.titleView=_searchBox;
}

//显示搜索历史记录列表
-(void)showSearchHistoryList{
    //隐藏历史记录为空页面
    [self hideHud];
    
    //切换状态
    _curStatus=SEARCH_VIEW_STATUS_HISTORY;
    
    //获取搜索记录列表数据
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    _historySearchArray=[defaults objectForKey:KEYNAME_SEARCHHISTORY_USER_DEFAULTS];
    
    [self.tableView reloadData];
    
    if ([_historySearchArray count]==0) {
        //提示”空历史记录“页面
        [self showHudByType:HUDTYPE_SEARCH_HISTORY];
    }
}

//显示搜索热词列表
-(void)showSearchHotList{
    //隐藏“历史搜索记录为空”的提示
    [self hideHud];
    
    //切换状态
    _curStatus=SEARCH_VIEW_STATUS_HOT;
    
    [self.tableView reloadData];
}

//点击“搜索”按钮触发事件
-(void)onSearchButtonActive:(id)sender{
    NSString *text=_searchBox.text;
    
    if (![text isEqualToString:@""]) {
        //添加到 历史搜索记录
        [self addSearchHistory:text];
        
        //发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SHOW_GOODSLIST object:text];
    }else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"搜索内容不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

//清除搜索记录
-(void)clearSearchHistory{
    _historySearchArray=nil;
    
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    
    [defaults setObject:nil forKey:KEYNAME_SEARCHHISTORY_USER_DEFAULTS];
    
    [self showSearchHistoryList];
}

//添加搜索记录
-(void)addSearchHistory:(NSString *)search{
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    
    NSArray *historyArray=[defaults objectForKey:KEYNAME_SEARCHHISTORY_USER_DEFAULTS];
    
    if (historyArray==nil) {
        historyArray=[[NSArray alloc]init];
    }
    
    //判断是否已存在该搜索项
    BOOL isExist=NO;
    for (NSString *itemText in historyArray) {
        if ([itemText isEqualToString:search]) {
            isExist=YES;
            break;
        }
    }
    
    if (!isExist) {
        NSMutableArray *newArray=[NSMutableArray arrayWithArray:historyArray];
        [newArray addObject:search];
        [defaults setObject:newArray forKey:KEYNAME_SEARCHHISTORY_USER_DEFAULTS];
    }
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_curStatus == SEARCH_VIEW_STATUS_HOT) {
        return [_searchHotArray count];
    }else{
        return [_historySearchArray count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"searchCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.textLabel.font=[UIFont fontWithName:FONT_NAME_DEFAULT size:17.0];
        cell.textLabel.textColor=[UIColor colorFromHexRGB:@"303030"];
        
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
        label.textAlignment=NSTextAlignmentRight;
        label.font=[UIFont fontWithName:FONT_NAME_DEFAULT size:12.0f];
        label.textColor=[UIColor colorFromHexRGB:@"b3b3b3"];
        cell.accessoryView=label;
    }
    
    UILabel *mylabel=(UILabel *)cell.accessoryView;
    mylabel.text=@"";
    
    if (_curStatus == SEARCH_VIEW_STATUS_HOT) {
        //搜索热词
        NSDictionary *dataDic=[_searchHotArray objectAtIndex:indexPath.row];
        NSString *text=[dataDic objectForKey:@"key"];
        int count=[[dataDic objectForKey:@"count"]intValue];
        cell.textLabel.text=text;
        mylabel.text=[NSString stringWithFormat:@"约%d个商品",count];
        
    }else{
        //搜索历史记录
        cell.textLabel.text=[_historySearchArray objectAtIndex:indexPath.row];
        
    }
    
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    UIView *view=[tableView footerViewForSection:section];
    
    if (view==nil) {
        view=[[UIView alloc] init];
        [view addSubview:_clearHistoryButton];
        _clearHistoryButton.hidden=YES;
    }
    
    
    if (_curStatus == SEARCH_VIEW_STATUS_HISTORY  && [_historySearchArray count]>0) {
        [view setFrame:CGRectMake(0, 0, kScreenWidth, 40)];
        CGFloat pointX=kScreenWidth/2 - 50;
        [_clearHistoryButton setFrame:CGRectMake(pointX, 5, 100, 30)];
        
        _clearHistoryButton.hidden=NO;
    }else{
        _clearHistoryButton.hidden=YES;
        [view setFrame:CGRectZero];
    }
    
    return view;
}



#pragma mark - Table view Delegate Method
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *selectText;
    if (_curStatus == SEARCH_VIEW_STATUS_HISTORY) {
        selectText=[_historySearchArray objectAtIndex:indexPath.row];
    }else{
        NSDictionary *dicData=[_searchHotArray objectAtIndex:indexPath.row];
        selectText=[dicData objectForKey:@"key"];
    }
    
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SHOW_GOODSLIST object:selectText];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}




#pragma mark - TextField Delegate Methods

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    NSString *text=textField.text;
    
    if ([text isEqualToString:@""]) {
        //显示历史搜索记录页面
        [self showSearchHistoryList];
    }else{
        //显示搜索热词页面
        [self showSearchHotList];
    }
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString *searchStr=_searchBox.text;
        
        if ([searchStr isEqualToString:@""]) {
            //显示搜索记录页面
            [self showSearchHistoryList];
        }else{
            //显示搜索 热词 页面
            [self showSearchHotList];
        }
    });
    
    NSLog(@"%@",textField.text);
    NSLog(@"%d",range.location);
    
    return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    //执行搜索操作,push商品列表页面
    [self showSearchHistoryList];
    
    return YES;
}

@end
